package sharetime.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

@SuppressWarnings("unchecked")
public class ClassLoaderUtils {

	public static Class loadClass(String className, Class callingClass)
			throws ClassNotFoundException {
		Class clazz = null;
		clazz = Thread.currentThread().getContextClassLoader().loadClass(
				className);
		if (clazz == null)
			clazz = Class.forName(className);
		if (null == clazz)
			clazz = (ClassLoaderUtils.class).getClassLoader().loadClass(
					className);
		if (null == clazz)
			clazz = callingClass.getClassLoader().loadClass(className);
		return clazz;
	}

	public static URL getResource(String resourceName, Class callingClass) {
		URL url = null;
		url = Thread.currentThread().getContextClassLoader().getResource(
				resourceName);
		if (url == null)
			url = ClassLoaderUtils.class.getClassLoader().getResource(
					resourceName);
		if (url == null)
			url = callingClass.getClassLoader().getResource(resourceName);
		return url;
	}

	public static Enumeration getResources(String resourceName,
			Class callingClass) throws IOException {
		Enumeration urls = Thread.currentThread().getContextClassLoader()
				.getResources(resourceName);
		if (urls == null) {
			urls = ClassLoaderUtils.class.getClassLoader().getResources(
					resourceName);
			if (urls == null)
				urls = callingClass.getClassLoader().getResources(resourceName);
		}
		return urls;
	}

	public static InputStream getResourceAsStream(String resourceName,
			Class callingClass) {
		URL url = getResource(resourceName, callingClass);
		try {
			return url == null ? null : url.openStream();
		} catch (IOException ex) {
			return null;
		}

	}

	public static void printClassLoader() {
		System.out.println("ClassLoaderUtils.printClassLoader");
		printClassLoader(Thread.currentThread().getContextClassLoader());
	}

	public static void printClassLoader(ClassLoader cl) {
		System.out
				.println("ClassLoaderUtils.printClassLoader(cl = " + cl + ")");
		if (cl != null)
			printClassLoader(cl.getParent());
	}
}
